package com.liujun.spring4x.demo.service;

import com.liujun.spring4x.demo.dao.LoginLogDao;
import com.liujun.spring4x.demo.dao.UserDao;
import com.liujun.spring4x.demo.domain.LoginLog;
import com.liujun.spring4x.demo.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户相关的业务操作
 *
 * @author liujun
 * @version 1.0
 * @date 2018-08-05 14:11:00
 */
@Service
public class UserServiceImpl implements UserService {

  /** 用户数据库操作 */
  private UserDao userDao;

  /** 用户登录日志操作 */
  private LoginLogDao loginLogDao;

  /**
   * 进行用户登录匹配操作
   *
   * @param userName 用户名
   * @param password 密码
   * @return true 匹配成功，false 匹配失败
   */
  @Override
  public boolean hasMatchUser(String userName, String password) {
    int count = this.userDao.getMatchCount(userName, password);;
    return count > 0 ? true : false;
  }

  /**
   * 查询用户名
   *
   * @param userName 用户名
   * @return 查询的用户信息
   */
  @Override
  public User findUserByUserName(String userName) {
    return userDao.findUserByUserName(userName);
  }

  /**
   * 用户登录积分更新，并添加日志操作
   *
   * @param user 用户信息
   */
  @Override
  @Transactional
  public void loginSuccess(User user) {
    user.setCredits(5 + user.getCredits());
    LoginLog log = new LoginLog();
    log.setUserId(user.getUserId());
    log.setIp(user.getLastIp());
    log.setLoginDate(user.getLastVisit());
    // 进行积分的更操作
    userDao.updateLoginInfo(user);
    // 插入登录日志
    loginLogDao.insertLoginLog(log);
  }

  @Autowired
  public void setUserDao(UserDao userDao) {
    this.userDao = userDao;
  }

  @Autowired
  public void setLoginLogDao(LoginLogDao loginLogDao) {
    this.loginLogDao = loginLogDao;
  }
}
